package com.zy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LittleDesire
 * @description 12模块上传控制器
 * @date 2022-04-07 周四 10:42
 * @since 17
 */
@RestController
@CrossOrigin
@RequestMapping("api")
public class ApiController {
    @PostMapping("u6")
    public Map<String,Object> upload1(MultipartFile file, String user, HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();
        String msg = "";
        if (file.isEmpty()) {
            msg = "上传失败";
            map.put("code", "401");
            map.put("msg", msg);
        } else {
            try {
                long fileSize = file.getSize();
                String fileName = file.getOriginalFilename();
                assert fileName != null;
                // lastIndexOf 指定子字符串最后一次出现的索引，如果没有出现，则返回-1 。
                // extension name 后缀名
                String fileExt = fileName.lastIndexOf(".") == -1 ? "" : fileName.toLowerCase().substring(fileName.lastIndexOf("."));
                // %tY%<tm%<td%<tH%<tM%<tS 年与日时分秒
                String filePath = req.getServletContext().getRealPath(String.format("uploads/%tY%<tm%<td", System.currentTimeMillis()));
                File f = new File(filePath);
                if (f.exists()) {
                    f.mkdirs();
                }
                msg = "上传成功：" + fileName;
                map.put("code", "200");
                map.put("msg", msg);
                map.put("user", user);
                file.transferTo(new File(filePath, fileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}
